from django.shortcuts import render
from django.conf import settings
from QQLoginTool.QQtool import OAuthQQ

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView,RetrieveAPIView

from oauth.models import OAuthQQUser
from oauth.serializers import OauthSerializer
from users.setializers import UserSerializer
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

from users.utils import merge_cart_cookie_to_redis


class OauthQQloginView(APIView):
    """
    qq 构造跳转链接
    """
    def get(self,request):
        """
        1.获取前端发送的验证数据
        2.验证前端发送的验证数据
        3.创建qq 对象
        4.创建跳转链接
        5.返回跳转链接
        :param request:
        :return:
        """
        # 1. 获取前端发送的验证数据
        state = request.query_params.get("next",None)
        # 2.验证前端发送的验证数据
        if not state:
            state = "/"
        # 3.创建qq 对象

        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI,state=state)

        # 4.创建跳转链接
        login_url = qq.get_qq_url()

        # 5. 返回跳转链接
        return Response({"login_url":login_url})


class OAUthView(APIView):
    """
    1.获取code zhi
    2.判断code 值是否传递过来
    3.通过code 获取access_tocken
    4.通过access_tocken 获取openid
t
    """
    def get(self,request):
        code = request.query_params.get("code",None)

        if not code:
            return Response({"errno":"缺少code 值"},status=400)

        state = "/"
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI,state=state)

        access_token = qq.get_access_token(code)

        # 4、通过access_token值获取opendi值
        openid = qq.get_open_id(access_token)

        # 判断openid 是否绑定过用户
        try:
            qq_user = OAuthQQUser.objects.get(openid =openid)
        except:
                # 如果未绑定
            tjs = TJS(settings.SECRET_KEY, 300)

            open_id = tjs.dumps({"openid":openid}).decode()

            return Response({"access_token":open_id})

        else:
            # 绑定过，则登录成功
            # 生成token 值
            user = qq_user.user
            # 手动创建令牌
            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            # 生成载荷部分
            payload = jwt_payload_handler(user)
            # 生成token
            token = jwt_encode_handler(payload)


            response =  Response({
                "token":token,
                "user_id":user.id,
                "username":user.username
            })

            # 合并购物车
            response= merge_cart_cookie_to_redis(request, user, response)
            return response

    def post(self,request):
        data = request.data
        ser =  OauthSerializer(data=data)
        ser.is_valid()
        print(ser.errors)
        ser.save()
        return Response(ser.data)

